﻿package com.peachcastle.tools
{	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Loader;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	/**
	 * 游戏截屏照相机
	 * @author Kevin
	 */
	public class GameCamera 
	{		
		// 
		private var _loaderList:Array = null;
		
		/**
		 * 游戏照相机
		 */
		public function GameCamera()
		{
			
		}
		
		/**
		 * 屏幕拍照
		 * @param	target	目标对象
		 * @param	range	截屏范围，值为NULL时则进行完整截屏
		 * @return	位图对象
		 */	
		public function takePhoto(target:DisplayObject, range:Rectangle = null):Bitmap
		{			
			// 存储容器中的图片
			_loaderList = [];
			setLoaderList(target as DisplayObjectContainer, _loaderList);
			
			// 构建数据
			var width:Number = target.width;
			var height:Number = target.height;
			
			//
			if (range != null)
			{
				width = range.width;
				height = range.height;
			}
			else
			{
				range = new Rectangle(0, 0, width, height);
			}			
			
			//
			var data:BitmapData = new BitmapData(target.width, target.height, true, 0x00FFFFFF); 		// 填充透明背景
			var output:BitmapData = new BitmapData(width, height, true, 0x00FFFFFF);					// 输出		
			
			// 隐藏图片
			showLoaders(false);
			
			// 拷贝范围像素
			data.draw(target, null, null, BlendMode.NORMAL, null, true);
			output.copyPixels(data, range, new Point());
			data.dispose();
			
			// 显示图片
			showLoaders(true);
			
			// 返回图片数据	
			return new Bitmap(output);
		}		
		
		/**
		 * 返回Loader代理显示对象的数据列表
		 * @param	container
		 * @return
		 */
		private function setLoaderList(container:DisplayObjectContainer,loaderList:Array):void
		{			
			for (var i:int = 0; i < container.numChildren; i++)
			{
				var child:DisplayObject = container.getChildAt(i);
				if (child is Loader)
				{					
					loaderList.push([child, child.parent]);
					continue;
				}
				
				//
				if (child is DisplayObjectContainer)
				{
					setLoaderList(child as DisplayObjectContainer, loaderList);
				}			
				
			}			
		}
		
		/**
		 * 是否显示Loader
		 * @param	isShow
		 */
		private function showLoaders(isShow:Boolean):void
		{			
			var list:Array = null;
			for (var i:int = 0; i < _loaderList.length; i++)
			{
				list = _loaderList[i];
				var clip:Loader = list[0];
				if (isShow == false)
				{					
					if (clip) clip.parent && clip.parent.removeChild(clip);
					continue;
				}
				
				//
				(list[1] as DisplayObjectContainer).addChild(clip);
			}
		}
		
	}
	
}